package com.qf.mao.servlet.course;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.mao.entity.Course;
import com.qf.mao.entity.RespBean;
import com.qf.mao.service.CourseService;
import com.qf.mao.utils.CommonsUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @author 啾咪小魔王
 * @date 2022/4/7 9:56
 * @since JDK 1.8
 */
@SuppressWarnings("all")
@WebServlet("/CourseServlet")
public class CourseServlet extends HttpServlet {
    CourseService courseService = new CourseService();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");
        if ("page".equals(action)) {
            request.getRequestDispatcher("/WEB-INF/jsp/courseList.jsp").forward(request, response);
        }else if ("data".equals(action)){
            List<Course> list = courseService.getCourse();
            ObjectMapper om = new ObjectMapper();
            String json = om.writeValueAsString(list);
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.write(json);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String courseName = request.getParameter("courseName");
        Integer integer = courseService.addCourse(courseName);
        response.setContentType("application/json;charset=utf-8");
        RespBean respBean =null;
        if (integer == CommonsUtils.ERROR_NAME) {
            respBean = RespBean.respError("课程名字重复，添加失败");
        }else if (integer == CommonsUtils.SUCCESS){
            respBean = RespBean.respSuccess("添加成功");
        }else {
            respBean = RespBean.respError("未知操作，添加失败");
        }
        ObjectMapper om = new ObjectMapper();
        String json = om.writeValueAsString(respBean);
        response.getWriter().write(json);
    }

    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String cid = request.getParameter("cid");
        Integer integer = courseService.deleteCourseByCid(cid);
        response.setContentType("application/json;charset=utf-8");
        RespBean respBean = null;
        if (integer == CommonsUtils.SUCCESS_DELETE) {
            respBean = RespBean.respSuccess("删除成功");
        }else {
            respBean = RespBean.respError("删除失败");
        }
        response.getWriter().write(new ObjectMapper().writeValueAsString(respBean));
    }
}
